package com.twang.stock.zq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.config.StockMsgSender;
import com.twang.stock.dto.EmailMessage;
import com.twang.stock.entity.User;
import com.twang.stock.entity.zq.ZhaiQuanMinutes;
//import com.twang.stock.es.ZhaiQuanMinutesRepository;
import com.twang.stock.mapper.UserMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Service
public class ZhaiQuanServcie {

//    @Autowired
//    private ZhaiQuanMinutesRepository zhaiQuanMinutesRepository;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  StockMsgSender stockMsgSender;

    @Autowired
    private CommonService commonService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    public void toDayMinuesMoneyCheck(ZhaiQuanMinutes zhaiQuanMinutes) throws InterruptedException {
        String redisKey = String.format(RedisKey.ZHAI_QUAN_MINUTES_VOL_CODE_LAST_MINUTES, zhaiQuanMinutes.getCode());

        //如果已经预警了，就推出
        String redisKeyWarn = String.format(RedisKey.LOCK_NEW_MINUTES_ID,zhaiQuanMinutes.getDate()+zhaiQuanMinutes.getCode());
        if(redisUtil.hasKey(redisKeyWarn)){
            return;
        }
        Object object = redisUtil.get(redisKey);
        if (null != object) {
            BigDecimal amount = zhaiQuanMinutes.getAmount().subtract(new BigDecimal(object.toString()));
            log.info(">>>>>>>>>> toDayMinuesMoneyCheck name={} amount={}  ", zhaiQuanMinutes.getName(), amount);
            if (amount.compareTo(new BigDecimal(900 * 10000)) > 0) {
                if (redisUtil.hasKey(redisKey + "warned")) {
                    //触发预警
                    String messages = new StringBuffer().append("触发分时涨幅超过900w!!!涨幅：").append(zhaiQuanMinutes.getChangePercent().setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
                    EmailMessage emailMessage = new EmailMessage();
                    emailMessage.setCode(zhaiQuanMinutes.getCode());
                    emailMessage.setName(zhaiQuanMinutes.getName());
                    emailMessage.setMessage(messages);
                    emailMessage.setType("5");
                    List<String> ids = Arrays.asList(commonService.getValue("WARN_ZHUANG_ZHAI_ID").toString().split(","));
                    for (String id : ids) {
                        User user = userMapper.selectByPrimaryKey(Long.valueOf(id));
                        emailMessage.setEmail(user.getEmail());
                        stockMsgSender.sendEmailMessage(JSONObject.toJSONString(emailMessage));
                    }
                    redisUtil.set(redisKey + "warned", zhaiQuanMinutes.getAmount(), 60 * 60 * 6);
                }
            }
        }
        redisUtil.set(redisKey, zhaiQuanMinutes.getAmount(), 60 * 60 * 23);
        redisUtil.set(redisKeyWarn, zhaiQuanMinutes.getAmount(), 60 * 60 * 23);

        try {
           // zhaiQuanMinutesRepository.save(zhaiQuanMinutes);
        } catch (Exception e) {
            log.error(">>>>>>>>> error toDayMinuesMoneyCheck e=", e);
        }
    }


    /**
     *
     * @param date
     * @param minutes
     * @throws InterruptedException
     */
    public void getzhuanzhaiList(String date,String minutes) throws InterruptedException {
        for (int i = 1; i <= 7; i++) {
            int finalI = i;
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                try {
                    String html = HtmlTools.getKezhuanZhaiList(String.valueOf(finalI)).get(0);
                    List<ZhaiQuanMinutes> zhaiQuanMinutesList = JSONArray.parseArray(html, ZhaiQuanMinutes.class);
                    zhaiQuanMinutesList.stream().forEach(item -> {
                        try {
                            item.setDate(date);
                            item.setMinutes(minutes);
                            toDayMinuesMoneyCheck(item);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    });
                } catch (Exception e) {
                    log.error(">>>>>>>>> 尾盘 执行选股 error={}", e);
                    throw new RuntimeException(e);
                }
            });
            Thread.sleep(100);
        }
    }
}
